package com.slkj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.CauseTaskDTO;
import com.slkj.dto.UserinfoDTO;
import com.slkj.entity.*;
import com.slkj.mapper.*;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CauseService {
    @Autowired
    CauseTaskMapper causeTaskMapper;

    @Autowired
    CauseNodeMapper causeNodeMapper;

    @Autowired
    CauseDutyMapper causeDutyMapper;

    @Autowired
    FileMapper fileMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    TaskService taskService;


    //打分
    public void point(String point, List<String> idList) {
        for (String id : idList) {
            if (!StringUtils.isNumeric(id)) {
                throw new RuntimeException("参数异常");
            }
            causeDutyMapper.point(point, id);
        }
    }


    //通过
    public void audit(List<String> idList, List<Map> variables, String count) {

        for (String id : idList) {
            CauseDuty causeDuty = causeDutyMapper.selectByDutyId(id);
            if (causeDuty.getCausePreAudit().equals("待审核")) {
                String light = "绿灯";
                taskComplete(variables, Integer.parseInt(count), id);
                causeDutyMapper.updateStatus(variables.get(0).get("isPass") + "", light, id);
            } else if (causeDuty.getCausePreAudit().equals("待上传") || causeDuty.getCausePreAudit().equals("未通过待上传")) {
                throw new RuntimeException("该任务待上传材料");
            } else {
                throw new RuntimeException("该任务已结束");
            }
        }
    }

    //驳回
    public void worry(List<String> idList, List<Map> variables, String count) {
        for (String id : idList) {
            CauseDuty causeDuty = causeDutyMapper.selectByDutyId(id);
            if (causeDuty.getCausePreAudit().equals("待审核")) {
                String light = "红灯";
                taskComplete(variables, Integer.parseInt(count), id);
                causeDutyMapper.updateStatus(variables.get(0).get("isPass") + "", light, id);
            } else if (causeDuty.getCausePreAudit().equals("待上传") || causeDuty.getCausePreAudit().equals("未通过待上传")) {
                throw new RuntimeException("该任务待上传材料");
            } else {
                throw new RuntimeException("该任务已结束");
            }
        }

    }

    //
    //亮灯调整以及原因
    public void why(String light, String why, List<String> idList, List<Map> variables) {
        for (String id : idList) {
            CauseDuty causeDuty = causeDutyMapper.selectByDutyId(id);
            if (causeDuty == null) {
                throw new NullPointerException("空指针异常");
            } else {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(causeDuty.getClass().getSimpleName().toLowerCase() + "/" + id).singleResult();
                ProcessInstance processInstancelight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(causeDuty.getClass().getSimpleName().toLowerCase() + "light/" + id).singleResult();

                if (processInstance != null) {
                    runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), "processInstance delete");
                }
                if (processInstancelight != null) {
                    runtimeService.deleteProcessInstance(processInstancelight.getProcessInstanceId(), "processInstance delete");
                }


                variables.get(0).put("causeName", causeDuty.getUsername());
                runtimeService.startProcessInstanceByKey("CauseName", causeDuty.getClass().getSimpleName().toLowerCase() + "light/" + id, variables.get(0));
                causeDutyMapper.updateStatus(variables.get(0).get("isPass") + "", light, id);
                causeDutyMapper.updateLightCase(why, id);
            }
        }

    }


    private Logger log = LoggerFactory.getLogger(CauseService.class);

    public void createTask(CauseTask causeTask, String username) {

        List<CauseNode> causeNodeList = causeTask.getCauseNodeList();
        List<String> causeUnitList = causeTask.getCauseUnitList();
        if (causeNodeList == null || causeUnitList == null) {
            throw new NullPointerException("参数异常");
        }

        if (causeNodeList.size() == 0 || causeUnitList.size() == 0) {
            throw new NullPointerException("参数异常");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        for (CauseNode causeNode : causeNodeList) {
            List<String> projectTime = causeNode.getProjectTime();
            try {
                causeNode.setCauseBeginTime(simpleDateFormat.parse(projectTime.get(0)));
                causeNode.setCauseEndTime(simpleDateFormat.parse(projectTime.get(1)));
            } catch (ParseException e) {
                log.error("日期格式转换异常");
                e.printStackTrace();
                throw new RuntimeException("日期格式转换异常");
            }
        }
        Userinfo userinfo = userMapper.selectByUsername(username);
        UserinfoDTO userinfoDTO = userService.getUserinfo(userinfo.getId());
        String type = userinfoDTO.getType();
        if (StringUtils.isBlank(type)) {
            throw new RuntimeException("任务发起人type为空");
        }
        causeTask.setUsername(userinfoDTO.getUsername());
        causeTask.setUserType(type);
        List<Userinfo> userinfoList = userMapper.selectByUserIdList(causeUnitList);


        //创建县区任务
        causeTaskMapper.insert(causeTask);
        SimpleDateFormat simpleDateFormatYear = new SimpleDateFormat("yyyy");


        for (CauseNode causeNode : causeNodeList) {
            causeNode.setCauseTaskId(causeTask.getId());
            causeNodeMapper.insert(causeNode);
            List<File> fileList = causeNode.getFileList();
            for (Userinfo userinfoUnit : userinfoList) {
                CauseDuty causeDuty = new CauseDuty();
                causeDuty.setCauseLight("灰灯");
                causeDuty.setCausePreAudit("待审核");
                causeDuty.setCauseYear(simpleDateFormatYear.format(new Date()));
                causeDuty.setUsername(userinfoUnit.getUsername());
                causeDuty.setName(userinfoUnit.getName());
                causeDuty.setUserId(userinfoUnit.getId());
                causeDuty.setCauseTaskId(causeTask.getId());
                causeDuty.setCauseNodeId(causeNode.getId());
                causeDutyMapper.insert(causeDuty);
                if (fileList != null && fileList.size() != 0) {
                    fileMapper.insert(fileList, causeDuty.getId(), "5");
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("causeName", causeDuty.getUsername());
                runtimeService.startProcessInstanceByKey("Cause", causeDuty.getClass().getSimpleName().toLowerCase() + "/" + causeDuty.getId(), map);
                taskComplete(null, 1, causeDuty.getId());

            }
        }


    }


    private void taskComplete(List<Map> mapList, int count, String dutyId) {
        CauseDuty causeDuty = causeDutyMapper.selectByDutyId(dutyId);
        String buniessKey = causeDuty.getClass().getSimpleName().toLowerCase() + "/" + causeDuty.getId();
        String buniessKeyLight = causeDuty.getClass().getSimpleName().toLowerCase() + "light/" + causeDuty.getId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
        ProcessInstance processInstanceLight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyLight).singleResult();
        ProcessInstance processInstanceTask = null;
        if (processInstance != null) {
            processInstanceTask = processInstance;
        } else if (processInstanceLight != null) {
            processInstanceTask = processInstanceLight;
        } else {
            throw new ActivitiException("找不到流程实例");
        }
        for (int i = 0; i < count; i++) {
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceTask.getProcessInstanceId()).taskAssignee(causeDuty.getUsername()).singleResult();
            if (mapList != null && mapList.size() != 0) {
                if (mapList.get(count - 1) != null) {
                    taskService.complete(task.getId(), mapList.get(count - 1));
                } else {
                    taskService.complete(task.getId());
                }
            } else {
                taskService.complete(task.getId());
            }
        }

    }

    public PageInfo<CauseTaskDTO> getTaskFeedback(String title, String userId, String light, Date beginDate, Date endDate, Integer page, Integer pageSize, String username, String status) {
        PageHelper.startPage(page, pageSize, true);
        List<CauseTaskDTO> causeTaskDTOList = causeDutyMapper.selectCauseTaskDTO(title, userId, light, beginDate, endDate, username, status);
        PageInfo pageInfo = new PageInfo<>(causeTaskDTOList);
        if (causeTaskDTOList != null) {
            List<File> fileList = fileMapper.selectByCauseTaskDTOList(causeTaskDTOList, "5");
            if (fileList != null && fileList.size() != 0) {
                for (CauseTaskDTO causeTaskDTO : causeTaskDTOList) {
                    boolean result = false;
                    List<File> causeFileList = new ArrayList<>();
                    for (File file : fileList) {
                        if (causeTaskDTO.getId().equals(file.getDutyId())) {
                            result = true;
                            causeFileList.add(file);
                        }
                    }
                    if (result) {
                        causeTaskDTO.setFileList(causeFileList);
                    }
                }
            }
        }
        return pageInfo;
    }

    //上传材料和追加材料
    public void taskUpload(List<File> fileList, String dutyId, List<Map> variables, String count) throws SQLException {
        CauseDuty causeDuty = causeDutyMapper.selectByDutyId(dutyId);
        if (causeDuty == null) {
            throw new SQLException("找不到该任务");
        }
        if (!causeDuty.getCausePreAudit().equals("待上传") && !causeDuty.getCausePreAudit().equals("未通过待上传")) {
            throw new RuntimeException("不能上传文件");
        }
        fileMapper.insert(fileList, dutyId, "5");
        taskComplete(variables, Integer.parseInt(count), dutyId);
        String audit = "待审核";
        String light = "黄灯";
        causeDutyMapper.updateStatus(audit, light, dutyId);
        causeDutyMapper.updateSubmitTime(new Date(), dutyId);
    }
}
